import org.junit.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Random;

// 批处理操作
public class Test02 {
    public static void main(String[] args) {

    }

    //产生指定长度的随机字符串
    public static String getRandomString(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(str.length());
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

//    随机插入100条数据，并读取打印
    @Test
    public void batch() {
        Connection connection = null;
        PreparedStatement statement = null;
//        ResultSet resultSet = null;

        try {
            JDBCUtiles.loadDriver();
            connection = JDBCUtiles.connection();
            String sql = "insert into crud values (?,?,?)";
            statement = connection.prepareStatement(sql);
            for (int i = 0 ; i < 101 ; i++) {
                statement.setInt(1,i);  // 设置第一个参数
                statement.setString(2,getRandomString(3));
                statement.setInt(3,new Random().nextInt(50));
                statement.addBatch();   // 添加到批处理命令
                if (i % 10 == 0) {
                    statement.executeBatch();   // 提交批处理
                    statement.clearBatch(); // 清空批处理
                }
            }
//            String query = "select * from crud";
//            statement.addBatch(query);
//            statement.executeBatch();
//            statement.clearBatch();

        }catch (Exception e) {
            e.printStackTrace();
        }finally {
//            JDBCUtiles.queryClose(connection,statement,resultSet);
            JDBCUtiles.close(connection,statement);
        }
    }

//    测试随机数函数
    @Test
    public void testRandomInt() {
        for (int i = 0 ; i < 10 ; i++) {
            System.out.println(new Random().nextInt(50));
        }
    }
}
